package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <b><code>CategoryController</code></b>
 * <p/>
 * 分类管理
 * <p/>
 * <b>Creation Time:</b> 24/06/2024 15:34.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@RequestMapping("/category")
@RestController
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        boolean flag = categoryService.save(category);
        if (flag) {
            return R.success("新增成功");
        }
        return R.error("新增失败");
    }

    /**
     * 菜品分页查询
     * @param page 当前页
     * @param pageSize 每页显示条数
     * @return 查询的分页结果
     */
    @GetMapping("/page")
    public R<Page<Category>> queryCategory(@RequestParam(name = "page") int page,
                                           @RequestParam(name = "pageSize") int pageSize) {
        return categoryService.queryCategory(page, pageSize);
    }

    /**
     * 删除分类
     * @param id 分类id
     * @return 是否成功
     */
    @DeleteMapping
    public R<String> deleteCategoryById(@RequestParam("id") Long id) {
        return categoryService.deleteCategoryById(id);
    }

    /**
     * 修改分类
     * @param category 分类信息
     * @return 修改是否成功
     */
    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        boolean flag = categoryService.updateById(category);
        if (flag) {
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }

    /**
     * 查询分类
     * @param category type 菜品 - 1，套餐 - 2
     * @return 分类结果
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType()).orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        return R.success(categoryService.list(queryWrapper));
    }

}
